//
//  QDStationsViewController.swift
//  QDMetroClient
//
//  Created by YueWen on 2019/2/24.
//  Copyright © 2019 YueWen. All rights reserved.
//

import UIKit

protocol QDStationsViewSelectAction: class {
    
    /// 站点信息点击
    func stationsViewController(didSelect stationName: String, stationId: String, line: [String])
}



extension QDStationsViewSelectAction where Self: QDStationsViewController {
    
    /// 站点信息点击
    func stationsViewController(didSelect stationName: String, stationId: String, line: [String]){
        
        /// 处理搜索模式
        func handleAtSelectPattern(){
            selectDelegate?.stationsViewController(didSelect: stationName, stationId: stationId, line: line)
            navigationController?.popViewController(animated: true)
        }
        
        switch type {
        case .select: handleAtSelectPattern()
        case .search: router(platform: .stationDetail(id: stationId, name: stationName, fromMap: false, delegate: nil))
        }
    }
    
}



/// 站点主控制器
final class QDStationsViewController: NWViewController,QDStationsViewSelectAction {

    /// 站点类型
    enum QDStationsType {
        /// 搜索模式
        case search
        /// 选择模式
        case select
    }
    

    
    /// 站点类型，默认为搜索模式
    var type = QDStationsType.search
    /// 选择状态的代理
    weak var selectDelegate: QDStationsViewSelectAction?

    // MARK: Datas
    
    /// 线路信息
    private var stationLines = [QDMetroLine]() {
        willSet {
            self.allStations = newValue.metroStationsWithoutRepeat()
            
        }didSet {
            stationsView.stationLines = stationLines
        }
    }
    
    /// 最近的站点
    private var nearStation = QDNearMetroStationContainer() {
        willSet {
            stationsView.nearStation = newValue
        }
    }
    
    /// 所有的站点，用于搜索
    private var allStations = [QDMetroStation]() {
        willSet {
            //赋值给搜索控制器
            resultView.allStations = newValue
        }
    }
    
    
    /// 导航视图，模拟导航栏
    private let navigationView = UIView()
    /// 模拟backItem的按钮
    private let backButton = UIButton()
    /// 取消按钮
    fileprivate let cancleButton = UIButton()
    /// 模拟导航的阴影
    fileprivate let shadowView = UIImageView()


    // 线路以及站点控制器
    lazy private var stationsView: QDStationsContainerViewController = {
        
        let stations = QDStationsContainerViewController()
        stations.view.isHidden = true
        stations.selectAction = self
        
        addChild(stations)
        view.addSubview(stations.view)
        
        stations.view.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(navigationView.snp.bottom)
        }
        
        return stations
    }()
    
    
    /// 搜索结果控制器
    lazy private var resultView: QDStationResultTableViewController = {
        
        let result = QDStationResultTableViewController()
        result.view.isHidden = true
        result.selectAction = self
        
        addChild(result)
        view.addSubview(result.view)
        
        result.view.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(navigationView.snp.bottom)
        }
        
        return result
    }()
    
    
    /// 搜索历史
    lazy private var historyView: QDStationHistoryViewController = {
        
        let history = QDStationHistoryViewController()
        history.view.isHidden = true
        history.selectActor = self
        
        addChild(history)
        view.addSubview(history.view)
        
        history.view.snp.makeConstraints { (make) in
            make.left.bottom.right.equalToSuperview()
            make.top.equalTo(navigationView.snp.bottom)
        }
        
        return history
        
    }()

    
    /// 导航栏的模拟搜索框
    fileprivate let textField = RITLSearchTextField()
    

    
    convenience init(type: QDStationsType = .search, delegate: QDStationsViewSelectAction? = nil) {
        self.init()
        selectDelegate = delegate
        self.type = type
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        /// 使用约束布局
        navigationView.backgroundColor = .white
        navigationView.clipsToBounds = false
        
        backButton.adjustsImageWhenHighlighted = false
        backButton.addTarget(self, action: #selector(nav_back), for: .touchUpInside)
        backButton.setImage("nav_back_default_custom".namedImage, for: .normal)
        
        shadowView.image = nav_shadowImage
        shadowView.backgroundColor = .white
        shadowView.isHidden = true //默认是隐藏
        
        view.addSubview(navigationView)
        navigationView.addSubview(backButton)
        navigationView.addSubview(shadowView)
        
        navigationView.snp.makeConstraints { (make) in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(BarDistance.NavigationBar.height + (76 - 64))
        }
        
        backButton.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(6)
            make.bottom.equalToSuperview().inset(18)
            make.height.equalTo(32)
            make.width.equalTo(32)
        }
        
        shadowView.snp.makeConstraints { (make) in
            make.bottom.equalToSuperview().inset(0.5)
            make.left.right.equalToSuperview()
            make.height.equalTo(5)
        }
        
        // 使用frame布局，便于动画
        
        let leftImageView = UIImageView(frame: CGRect(origin: .zero, size: CGSize(width: 19, height: 19)))
        leftImageView.image = "sta_search".namedImage
        
        textField.backgroundColor = #colorLiteral(red: 0.7607843137, green: 0.768627451, blue: 0.7647058824, alpha: 1).withAlphaComponent(0.2)
        textField.font = Font.regular.font(size: 16)
        textField.searchIconLeftMargin = 12
        textField.textLeftMargin = 4
        textField.textColor = QDColors.black
        textField.delegate = self
        textField.clearButtonMode = .whileEditing
        textField.tintColor = QDColors.theme
        textField.returnKeyType = .search
        
        // 左侧搜索框
        textField.leftView = leftImageView
        textField.leftViewMode = .always
        
        textField.attributedPlaceholder = NSAttributedString(string: "请输入搜索的站点", attributes:
            [.foregroundColor : 179.ritl_color,
             .font: Font.regular.font(size: 14)])
        
        textField.layer.cornerRadius = 18
        textField.clipsToBounds = true
        textField.delegate = self
        
        var width = ritl_width - 45 - 20
        textField.frame = CGRect(x: 45, y: 24 + BarDistance.NavigationBar.safeDistance, width: width, height: 36)
        navigationView.addSubview(textField)
        

        cancleButton.adjustsImageWhenHighlighted = false
        cancleButton.setTitle("取消", for: .normal)
        cancleButton.setTitleColor(QDColors.theme, for: .normal)
        cancleButton.titleLabel?.font = Font.regular.font(size: 14)
        cancleButton.ritl_size = CGSize(width: 28, height: 20)
        cancleButton.isHidden = true//默认隐藏
        cancleButton.addTarget(self, action: #selector(cancleButtonDidTap), for: .touchUpInside)
        
        width = ritl_width - 20 - 28 // 减去右边距20 以及自身长度
        cancleButton.ritl_originPoint = CGPoint(x: width, y: 32 + BarDistance.NavigationBar.safeDistance)
        navigationView.addSubview(cancleButton)
        
        //请求
        requestAllStations()
    }
    
    
    // MARK: NavigationBar
    override var nav_barHidden: Bool { return true }
    
    
    /// 取消按钮进行点击
    @objc func cancleButtonDidTap(){
        //
        textField.text = nil
        textField.resignFirstResponder()
        endEdit()
        showStationView()
    }
    
    /// 显示站点视图
    private func showStationView(){
        
        if !stationsView.view.isHidden { return }
        
        stationsView.view.isHidden = false
        historyView.view.isHidden = true
        resultView.view.isHidden = true
        shadowView.isHidden = true
    }
    
    /// 显示历史视图
    private func showHistoryView(){
        
        if !historyView.view.isHidden { return }
        
        stationsView.view.isHidden = true
        historyView.view.isHidden = false
        resultView.view.isHidden = true
        shadowView.isHidden = false
    }
    
    /// 显示搜索结果视图
    private func showResultView(){
        
        if !resultView.view.isHidden { return }
        
        stationsView.view.isHidden = true
        historyView.view.isHidden = true
        resultView.view.isHidden = false
        shadowView.isHidden = false
    }
    
    
    /// 请求所有的站点信息
    func requestAllStations(){
        
        view.showWatingHUD()
        QDNetworkingManager.requestAllStations(complete: { (near, stationLines) in
            
            self.view.dismissHUD()
            
            //获得所有的数据
            self.nearStation = near
            self.stationLines = stationLines
            self.showStationView()// 展示站点
            
        }) { (msg, errorType) in
            self.view.showTextHUD(text: msg)
        }
    }
}


extension QDStationsViewController: QDStationResultTableViewAction {
    
    func stationResultTableViewController(viewController: QDStationResultTableViewController,textFieldShouldFill stationName: String, stationId: String, line: [String]) {
        
        //进行填充
        textField.text = stationName
        
        //针对点击进行存储
        historyView.insertStation(stationName: stationName, stationId: stationId, lines: line)
    }
}


extension QDStationsViewController: UITextFieldDelegate {
    
    /// 进入编辑模式
    fileprivate func enterEdit(){
        
        UIView.animate(withDuration: 0.1, delay: 0, options: .curveEaseIn, animations: {
            
            self.textField.ritl_width = self.ritl_width - 45 - 64
            self.cancleButton.isHidden = false
            
        }, completion: nil)
    }
    
    /// 结束编辑模式
    fileprivate func endEdit(){
        
        UIView.animate(withDuration: 0.1, delay: 0, options: .curveEaseOut, animations: {
            
            self.textField.ritl_width = self.ritl_width - 45 - 20
            self.cancleButton.isHidden = true
            
        }, completion: nil)
    }
    
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        
        //只有不存在值的时候才进行进入模式
        if let text = textField.text, text.isEmpty, cancleButton.isHidden {
            enterEdit()
            showHistoryView()
        }
        
        return true
    }
    
    
    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        
        showHistoryView()//展示历史
        return true
    }
    
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        
        textField.resignFirstResponder()//结束响应
        showResultView()//显示结果
        
        if let text = textField.text {
            resultView.search(key: text)
        }
        
        return true
    }
    
}
